import axios from 'axios';
import { showFailToast, showSuccessToast } from 'vant';
import config from './config.ts';
/* import 'vant/es/toast/style'; *///这小子害死我了
import router from '../router/index';
import { refreshToken,clearExpiredRequest } from './index';
export default function $axios(Option: any) {
    return new Promise((resolve, reject) => {
        const instance = axios.create({
            baseURL: config.baseUrl,
            timeout: config.timeout
        });
        //请求拦截
        instance.interceptors.request.use((conf) => {
            const accessToken = localStorage.getItem('accessToken');//存在token就携带
            if (accessToken) {
                conf.headers['Authorization'] = `${accessToken}`
            } else if (conf.url !== '/login') {
                showFailToast('请先登录')
                router.push('/login')
            }
            
            return conf;
        },
            error => {
                console.log(error);
            }
        ),
            //响应拦截
            instance.interceptors.response.use(response => {
                const data = response.data;
                console.log('data',data);
                
                if (data.code >= 200 && data.code < 300) {
                    data.message && showSuccessToast(data.message);
                }
                if (data.code == 206) {
                    console.log(12234564);
                    localStorage.setItem('accessToken', data.accessToken)
                    localStorage.setItem('refreshToken', data.refreshToken)
                }
                return data;
            }, err => {
                if (err && err.response) {
                    
                    switch (err.response.status) {
                        case 400:
                            err.message = '请求错误'
                            break;
                        case 401:
                            err.message = '未授权，请登录'
                            clearExpiredRequest();
                            router.push('/login');
                            break;
                        case 402:
                            err.message = ''
                            console.log(err);
                            refreshToken(()=>Promise.resolve(instance(err.config)))
                            break;
                        case 404:
                            err.message = '请求地址出错'
                            break;
                        default:
                            err.message = '未知错误'
                            break;
                    }
                }
                err.message && showFailToast(err.message)
                return Promise.reject(err)
            }
            ),
            //请求
            instance(Option).then((res) => {
                resolve(res);
            }).catch(err => {
                reject(err);
            })

    })
}



